//
//  GoodsOrderListCtr-cell.swift
//  smosky
//
//  Created by zhuxietong on 2018/7/5.
//  Copyright © 2018年 tianrun. All rights reserved.
//

import Foundation
import AsyncDisplayKit
import soapp
import Eelay

extension Goods
{
    
    open class BtsStatusCell: JoCellNode {
        
        open class SellerNode: MoDisplayNode {
            public let logoV = JoImageNode()
            public let titleL = ASTextNode()
            
            public let line = ASDisplayNode()
            public let topline = ASDisplayNode()
            
            public let statusL = ASTextNode()
            public let markNode = EeMarkNode()
            
            
            override open func mo_model_reload() {
//                print("+++dddd++OOOOO11|\(mo.model)")

                markNode.msgType = GMsgType.goods_order.msg
                markNode.markID = mo.model["order.id",""]
                logoV.img_url = mo.model["logo",""]
                titleL.attributedText = mo.model["merchname",""].ui.font14.color(color: ._foreground).astring
                line.backgroundColor = UIColor._separator
                topline.backgroundColor = UIColor._tableBackground
                view.backgroundColor = ._cellBackground
            }
            
            override open func specGetter() -> _Spec {
                let content:_Spec = .stack(["h|10",_nowrap,&-.center,_justfy(.space_between)], childs: [
                    _Spec.stack(["h|8",_shrink(1),&-.center], childs: [
                        logoV["20",20],
                        titleL.Spec
                        ]),
                    _Spec.stack(["h|8",_shrink(1),&-.center], childs: [
                        statusL[_shrink(1),[0,0,0,8]],
//                        markNode.Spec
                        ]),
                    ])
                
                return .stack(["v",&-.stretch], childs: [
                    topline["8"],
                    .inset([], [8,AppTheme.edge], child: content),
                    line["\(TP.separatorHeight)"],
                    ])
            }
        }
        
        
        let bt1 = ASButtonNode()
        let bt2 = ASButtonNode()
        let bt3 = ASButtonNode()
        
        var status:GoodsOrderStatus = .all{
            didSet{
                
            }
        }
        var sellerV = SellerNode()
        
        
        override open func addLayoutRules() {
            bt1.addTarget(self, action: #selector(buttonAction(sender:)), forControlEvents: .touchUpInside)
            bt2.addTarget(self, action: #selector(buttonAction(sender:)), forControlEvents: .touchUpInside)
            bt3.addTarget(self, action: #selector(buttonAction(sender:)), forControlEvents: .touchUpInside)
            view.backgroundColor = ._tableBackground
        }
        
        var isListCell:Bool{
            get{
                if mo.model.possible("__model.order.status", default: "") == ""
                {
                    return true
                }
                else{
                    return false
                }
            }
        }
        
        open override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
            mo_model_reload()
        }
        override open func mo_model_reload() {
            
//            print("====+___+++++++D+D++DL|\(mo.model)")
            
            let statusV =  mo.model.possible("order.status","__model.order.status", default: "")
            self.status = GoodsOrderStatus(rawValue: statusV) ?? .all
            sellerV.statusL.attributedText = mo.model["order.statusstr",""].loc.ui.color(color: ._foreground).font12.astring
            let bts = status.actionButtons
            bts.0.assign(to: bt1).run()
            bts.1.assign(to: bt2).run()
            
                        
            var specs = [_Spec]()
            if !bt1.isHidden
            {
                specs.append(bt1.Spec)
            }
            if !bt2.isHidden
            {
                specs.append(bt2.Spec)
            }
            
            
            if !isListCell
            {
                switch self.status{
                case .待发货:
                    let goods = SaleAfterType.validAfterSeverGoods(order: DataNode.path(node: "__model", mo.model, value: NSMutableDictionary()))
                    if goods.count > 0 {
                        if OrderScheme.default.supportSaleAfter{
                            bt3.ui.hidden(hidden: false).padding(insets: [6,12]).ncolor(color: ___shop.tint).font(font: UIFont.systemFont(ofSize: 12)).ntitle(title: "申请退款".loc).set(radius: 3, width: 1, color: ___shop.tint)
                            specs.append(bt3.Spec)
                        }
                    }
                case .已收货:
                    let goods = SaleAfterType.validAfterSeverGoods(order: DataNode.path(node: "__model", mo.model, value: NSMutableDictionary()))
                    if goods.count > 0
                    {
                        if OrderScheme.default.supportSaleAfter{
                            bt3.ui.hidden(hidden: false).padding(insets: [6,12]).ncolor(color: ___shop.tint).ntitle(title: "申请售后".loc).font(font: UIFont.systemFont(ofSize: 12)).set(radius: 3, width: 1, color:___shop.tint)
                            specs.append(bt3.Spec)
                        }
                    
                        
                    }
                default:
                    break
                }
            }
            
            btSpecs = specs
            
        }
        
        var btSpecs = [_Spec]()
        var actionBarSpec:_Spec?{
            get{
                if btSpecs.count > 0
                {
                    
                    return _Spec.stack(["v",_shrink(1),_justfy(.space_between),&-.stretch], childs: [
                        .stack(["h|10",[10,AppTheme.edge,16,AppTheme.edge],&-.center,_justfy(.flex_end)], childs: btSpecs)
                        ])
                }
                else{
                    return nil
                }
            }
        }
        
        override open func specGetter() -> _Spec {
            
            var list: [_Spec] = [
            ]
            if let bar = self.actionBarSpec
            {
                list.append(bar)
            }
            let spec = _Spec.stack(["v",_shrink(1),_justfy(.space_between),&-.stretch], childs: list)
            return spec
            
            //            let spec = _Spec.stack(["v",_shrink(1),_justfy(.space_between),&-.stretch], childs: [
            //                .stack(["h|10",[10,AppTheme.edge,26,AppTheme.edge],&-.center,_justfy(.flex_end)], childs: [
            //                    bt1.Spec,
            //                    bt2.Spec
            //                    ])
            //                ])
            //            return spec
            
        }
        
        @objc func buttonAction(sender:ASButtonNode)  {
            weak var wself = self
            var model = mo.model
            if let __model = DataNode<NSMutableDictionary>.path(node: "__model", mo.model)
            {
                
                model = __model
            }
            self.status.doAction(with: sender.actionID, cell: wself, at: content_controller, order: model)
            
        }
    }
    
    public class OrderListCell:BtsStatusCell,EeActionDelegate{
        let markL = EeMarkNode()
        
        public func active(onwer: Any, actionID: String, data: NSMutableDictionary) {
            Goods.seeDetail(obj: data, at: content_controller)
         
        }
        
        
        //详情页没有顶部空白
        public class SellerNode1: SellerNode {
            
            override public func mo_model_reload() {
//                print("+++++OOOOO11|\(mo.model)")
                
                logoV.img_url = mo.model["logo",""]
                titleL.attributedText = mo.model["merchname",""].ui.font14.color(color: ._foreground).astring
                line.backgroundColor = UIColor._cellBackground
                topline.backgroundColor = UIColor._cellBackground
            }
            
            
            override public func specGetter() -> _Spec {
                //                let content:_Spec = .stack(["h|10",_nowrap,&-.center,], childs: [
                //                    logoV["20",20],
                //                    titleL.Spec
                //                    ])
                
                let content:_Spec = .stack(["h|10",_nowrap,&-.center,_justfy(.space_between)], childs: [
                    _Spec.stack(["h|8",_shrink(1)], childs: [
                        logoV["20",20],
                        titleL.Spec
                        ]),
                    statusL[_shrink(1)],
                    ])
                
                return .stack(["v",&-.stretch], childs: [
                    topline["2"],
                    .inset([], [8,AppTheme.edge], child: content),
                    line["\(TP.separatorHeight)"],
                    ])
            }
        }
        
      
        
        
        class GoodsKit: JoTouchNode {
            
            let imgV = JoImageNode()
            let titleL = ASTextNode()
            let priceL = ASTextNode()
            let specL = ASTextNode()
            
            let line = ASDisplayNode()
            let numL = ASTextNode()
            
            
            
            
            override func addLayoutRules() {
                titleL.maximumNumberOfLines = 2
                self.backgroundColor = ._cellBackground
                line.backgroundColor = UIColor._separator
                imgV.isUserInteractionEnabled = true
                imgV.view.isUserInteractionEnabled = true
                let tap = UITapGestureRecognizer(target: self, action: #selector(seeGoods))
                imgV.view.addGestureRecognizer(tap)
            }
            
            @objc func seeGoods() {
                active(ID: "openGoods")
                //            self.delegate?.active(onwer: self, actionID: "openGoods", data: mo.model)
            }
            
            override open func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec {
                return fastLayoutSpec(_spec: specGetter())
            }
            
            override func specGetter() -> _Spec {
                
                let content:_Spec = .stack(["h|10",_shrink(1),&-.stretch,_nowrap], childs: [
                    imgV["\(63)",63],
                    .stack(["v",_shrink(1),_justfy(.space_between),_grow(1),&-.stretch], childs: [
                        .stack(["h|10",&-.flex_start,_nowrap,_justfy(.space_between)], childs: [
                            titleL[_shrink(1)],
                            priceL.Spec,
                            ]),
                        .stack(["h|10",&-.flex_start,_nowrap,_justfy(.space_between)], childs: [
                            specL[_shrink(1)],
                            numL.Spec,
                            ]),
                        ])
                    ])
                
                var items:[_Spec] = [
                    .inset([], [8,AppTheme.edge], child: content),
                    ]
                if mo.model["__last__",FK.NO] == FK.YES{
                }else{
                    items.append(line["\(TP.separatorHeight)"])
                }
                
                return .stack(["v",&-.stretch], childs:items)
            }
            
            
            
            override func mo_model_reload() {
                imgV.imageView?.ui.holder(type: .grayBack)
                
                imgV.img_url = mo.model["thumb",""]
                let price = mo.model.possible("marketprice","price", default: "0")
                
                priceL.attributedText =  "¥ \(price.cg_floatValue.price_display)".ui.font12.color(color: ___shop.second).font13.astring
                
                titleL.maximumNumberOfLines = 2
                
                titleL.attributedText = mo.model["title",""].ui.color(color: ._foreground).font13.lineSpace(5).astring
                
                specL.maximumNumberOfLines = 1
                
                specL.attributedText = mo.model["optiontitle",""].ui.cl_888.font12.lineSpace(5).astring
                
                numL.maximumNumberOfLines = 1
                numL.attributedText = "x\(mo.model["total","1"])".ui.font13.cl_888.astring
                
            }
        }
        
        let goodsV = JoRuleNode<GoodsKit>()
        
        let sumL = ASTextNode()
        
        let sumL_line = ASDisplayNode()
        
        
        override public func addLayoutRules() {
            super.addLayoutRules()
            markL.msgType = GMsgType.goods_order.msg
            
        }
        
        override public func willLayoutRules() {
            goodsV.nodePath = "order.goods"
        }
        override public func mo_model_reload() {
            
            super.mo_model_reload()
            var model = mo.model
            if let __model = DataNode<NSMutableDictionary>.path(node: "__model", mo.model)
            {
                
                model = __model
            }
            
            goodsV.containerConfig = {
                spec in
                spec.alignItems = ASStackLayoutAlignItems.stretch
                spec.direction = ASStackLayoutDirection.vertical
            }
            sellerV.mo.model = model
            goodsV.mo.model = model
            goodsV.space = 0
            backgroundColor = ._cellBackground
            
            goodsV.delegate = self
            let goods = DataNode.path(node: "order.goods", model, value: NSMutableArray())
            var num = 0
            goods.list { (one:NSMutableDictionary, i) in
                let one_num = one[int:"total",0]
                num = num + one_num
            }
            
            let price = model[float:"order.price",0]
            let str = "共计[XX]件商品 合计：[YY] [ZZ]".replaceVars(values: "\(num)",price.price_display,"¥".loc)
            sumL.attributedText = str.ui.font14.color(color: .color(light: "#444", dark: "#ccc")).right.astring
            
            let orderid = mo.model["order.id",""]
            markL.markID = orderid
            sumL_line.backgroundColor = UIColor._separator
            
            if isListCell{
                goodsV.isUserInteractionEnabled = false
            }
        }
        
        
        var orderID:String{
            get{
                
                var model = mo.model
                if let __model = DataNode<NSMutableDictionary>.path(node: "__model", mo.model)
                {
                    model = __model
                }
                let id = model["id",""]
                
//                let ctr = 订单支付Ctr()
//                ctr.mo.model = order
//                controller?.navigationController?.pushViewController(ctr, animated: true)
                return id
            }
        }
        
        
        
        override public func specGetter() -> _Spec {
            
            var list: [_Spec] = [
                sellerV.Spec,
                goodsV.Spec,
                sumL[[16,AppTheme.edge,16,AppTheme.edge]],
            ]
            if let bar = self.actionBarSpec
            {
                list.append(bar)
            }
            let spec = _Spec.stack(["v",_shrink(1),_justfy(.space_between),&-.stretch], childs: list)
            
            let back = _Spec.over([], over: .stack(["h",_justfy(.flex_end)], childs: [
                markL[[22,0,8,12]]
                ]), back: spec)
//            let over = _Spec.back([], over: .stack(["h"], childs: [
//                markL.Spec
//                ]), back: spec)
            return back
            
        }
    }
    
}


